import random
from django.db import IntegrityError
from django.utils import timezone
from rest_framework import filters, status
from rest_framework.decorators import api_view
from rest_framework.generics import CreateAPIView, RetrieveAPIView, RetrieveUpdateAPIView, ListAPIView, DestroyAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from answer.models import Answer
from questions.models import Question, Banner, QuestionPicture, QuestionPraiseRelationship, QuestionFocus
from questions.serializer import QuestionDetailSer, QuestionCreateSer, QuestionListSer, BannerSer, QuestionTrueSer, \
    QuestionFalseSer, QuestionRandomDetailSer, QuestionFocusListSer, QuestionFocusCreateSer
from tag.models import Tag
from utils.order_list import INIT_CORE, DAYS
from utils.permission import IsOwnerOrReadOnly


class QuestionCreateView(CreateAPIView):
    serializer_class = QuestionCreateSer

    def perform_create(self, serializer):
        # deal with tag
        tags_str = self.request.data.get('tag', None)
        picture_str = self.request.data.get('pictures', None)
        tag_list = []
        picture_list = []
        if tags_str:
            for tag_str in tags_str.split("|"):
                tag = Tag.objects.get_or_create(name=tag_str)[0]
                tag_list.append(tag)
        if picture_str:
            for i in picture_str.split(" "):
                img = QuestionPicture.objects.create(image=i)
                picture_list.append(img)
        serializer.save(creator=self.request.user, tags=tag_list, pictures=picture_list)


class QuestionDetailView(RetrieveAPIView):
    queryset = Question.objects.all()
    serializer_class = QuestionDetailSer


class QuestionUpdateView(RetrieveUpdateAPIView):
    permission_classes = (IsOwnerOrReadOnly,)
    queryset = Question.objects.all()
    serializer_class = QuestionDetailSer

    def perform_update(self, serializer):
        tags_str = self.request.data.get('tag', None)
        picture_str = self.request.data.get('pictures', None)
        tag_list = []
        picture_list = []
        if tags_str:
            for tag_str in tags_str.split("|"):
                tag = Tag.objects.get_or_create(name=tag_str)[0]
                tag_list.append(tag)
        if picture_str:
            for i in picture_str.split(" "):
                img = QuestionPicture.objects.create(image=i)
                picture_list.append(img)
        serializer.save(creator=self.request.user, tags=tag_list, pictures=picture_list, partial=True)


class QuestionListView(ListAPIView):
    filter_backends = (filters.SearchFilter,)
    search_fields = ('title',)
    serializer_class = QuestionListSer
    queryset = Question.objects.all()

    def list(self, request, *args, **kwargs):

        def flag(x):
            score = INIT_CORE
            now = timezone.now()
            if request.user.expertise_area in x.tags.all():
                score += 3000
            time_range = (now - x.created_time).days
            if time_range >= DAYS:
                score -= INIT_CORE
            else:
                score = score - time_range * 100
            shoucang_score = QuestionFocus.objects.filter(question=x).count() * 500
            huida_score = Answer.objects.filter(question=x).count() * 250
            score = score + shoucang_score + huida_score
            # print(score)
            return score

        tag = request.query_params.get('tag')
        queryset = self.filter_queryset(self.get_queryset())
        # deal with tag
        if tag:
            queryset = queryset.filter(tags__name__exact=tag).order_by('-created_time')
        queryset = list(sorted(queryset, key=flag, reverse=True))
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


class QuestionDeleteView(DestroyAPIView):
    permission_classes = (IsOwnerOrReadOnly,)
    queryset = Question.objects.all()
    serializer_class = QuestionDetailSer


class RandomQuestionView(APIView):
    """随机查看一条问题"""

    def get(self, request, **kwargs):
        user = request.user
        count = Question.objects.count()
        i = random.randint(0, count)
        question = Question.objects.all()[i]
        rdict = QuestionRandomDetailSer(question).data
        # try:
        #     qrl = QuestionPraiseRelationship.objects.get(question=question, user=user)
        # except QuestionPraiseRelationship.DoesNotExist:
        #     qrl = QuestionPraiseRelationship.objects.create(question=question, user=user)
        # rdict['is_praised'] = True if qrl.praise == 1 else False
        return Response(rdict)


class BannerCreateView(CreateAPIView):
    # permission_classes = (IsAdminUser,)
    queryset = Banner.objects.all().order_by('index')
    serializer_class = BannerSer


class BannerListView(APIView):
    def get(self, request, **kwargs):
        banners = Banner.objects.all()
        ser = BannerSer(data=banners, many=True)
        if ser.is_valid():
            ser.save()
        return Response({'banner': ser.data})


@api_view(['POST'])  # 给问题点赞
def praise_question(request, **kwargs):
    question_id = kwargs.get('pk')
    try:
        question = Question.objects.get(id=int(question_id))
    except Question.DoesNotExist:
        return Response({"detail": "question does not found."}, status=404)
    user = request.user
    try:
        qrl = QuestionPraiseRelationship.objects.get(question=question, user=user)
    except QuestionPraiseRelationship.DoesNotExist:
        qrl = QuestionPraiseRelationship.objects.create(question=question, user=user)
    if qrl.praise is False:
        qrl.praise = True
        question.praise += 1
        question.save()
        qrl.save()
        return Response(QuestionTrueSer(question).data, status=201)
    if qrl.praise is True:
        qrl.praise = False
        question.praise -= 1
        question.save()
        qrl.save()
        return Response(QuestionFalseSer(question).data, status=201)


# -------------------------------------------------------------------

class QuestionFocusListView(ListAPIView):
    serializer_class = QuestionListSer

    def get_queryset(self):
        user = self.request.user
        queryset = Question.objects.filter(questionfocus__creator=user).order_by('-created_time')
        return queryset


class QuestionFocusCreateView(CreateAPIView):
    serializer_class = QuestionFocusCreateSer

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        question_id = self.request.data.get('question')
        try:
            question = Question.objects.get(id=question_id)
            serializer.save(question=question)
        except Question.DoesNotExist:
            return Response({"detail": "question does not exist"})
        except IntegrityError:
            return Response({"detail": "This problem has been concerned"})
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)


class QuestionFocusDeleteView(DestroyAPIView):
    lookup_field = 'question'  # 传问题id
    permission_classes = (IsOwnerOrReadOnly,)
    queryset = QuestionFocus.objects.all()
    serializer_class = QuestionFocusListSer

# class TuijianView(APIView):
#
#     def get(self, request, **kwargs):
#         questions = Question.objects.all().order_by('-praise')[:2]
#         answers = Answer.objects.all().order_by('-praise')[:2]
#         question_ser = TuijianQuestion(data=questions, many=True)
#         if question_ser.is_valid():
#             question_ser.save()
#         answer_ser = TuijianAnswer(data=answers, many=True)
#         if answer_ser.is_valid():
#             answer_ser['type'] = 'answer'
#             answer_ser.save()
#         data = question_ser.data+answer_ser.data
#         return Response({'banner': data})
